package com.pig4cloud.pigx.wxApi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pigx.common.core.util.R;
import com.pig4cloud.pigx.ruralLibrary.api.entity.BookDataTypeEntity;
import com.pig4cloud.pigx.ruralLibrary.api.entity.BookTypeEntity;
import com.pig4cloud.pigx.ruralLibrary.api.entity.RecommendManageEntity;
import com.pig4cloud.pigx.ruralLibrary.api.entity.ResourceEntity;
import com.pig4cloud.pigx.wxApi.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import nl.siegmann.epublib.domain.Book;
import nl.siegmann.epublib.epub.EpubReader;

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
@Slf4j
public class appInterfaceServiceImpl implements appInterfaceService {

    @Autowired
    private RecommendManageService recommendManageService;
    @Autowired
    private ResourceService resourceService;
    @Autowired
    private BookDataTypeService dataTypeService;
    @Autowired
    private BookTypeService bookTypeService;
    private Map<String,String> map;
    public R getProductResources() {
        List<Map> list = new ArrayList<>();

        LambdaQueryWrapper<ResourceEntity> recommendManageWrapperwrapper = Wrappers.lambdaQuery();
        recommendManageWrapperwrapper.ne(ResourceEntity::getCover, "http://61.163.243.7:9999/digitallibrary/file/lengleng/暂无封面.jpg");
        recommendManageWrapperwrapper.orderByDesc(ResourceEntity::getPageView);
        recommendManageWrapperwrapper.isNotNull(ResourceEntity::getBriefIntroduction);
        recommendManageWrapperwrapper.last("LIMIT 6");
        List<ResourceEntity> list2 = resourceService.list(recommendManageWrapperwrapper);
        Map map1 = new HashMap();
        map1.put("dataTypeId", null);
        map1.put("dataType", "热门推荐");
        map1.put("resource", list2);
        list.add(map1);

        LambdaQueryWrapper<BookDataTypeEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(BookDataTypeEntity::getDataTypeStatus, "1");
        for (BookDataTypeEntity bookDataTypeEntity : dataTypeService.list(wrapper)) {
            Map map = new HashMap();
            map.put("dataTypeId", bookDataTypeEntity.getId());
            map.put("dataType", bookDataTypeEntity.getDataType());
            LambdaQueryWrapper<ResourceEntity> Wrapper = Wrappers.lambdaQuery();
            Wrapper.eq(ResourceEntity::getDataTypeId, bookDataTypeEntity.getId());
            Wrapper.isNotNull(ResourceEntity::getBriefIntroduction);
            Wrapper.orderByDesc(ResourceEntity::getPageView);
            Wrapper.last("LIMIT 6");
            List<ResourceEntity> list1 = resourceService.list(Wrapper);
            map.put("resource", list1);
            list.add(map);
        }
        return R.ok(list);
    }

    @Override
    public R getTypeResources(Long id) {
        List<Map> list = new ArrayList<>();
        LambdaQueryWrapper<BookTypeEntity> wrapper = Wrappers.lambdaQuery();
//        wrapper.eq(BookTypeEntity::getDataTypeStatus, "0");
        wrapper.eq(BookTypeEntity::getDatatypeId, id);
        for (BookTypeEntity type : bookTypeService.list(wrapper)) {
            Map map = new HashMap();
            map.put("dataTypeId", type.getId());
            map.put("name", type.getBookType());
            LambdaQueryWrapper<ResourceEntity> Wrapper = Wrappers.lambdaQuery();
            Wrapper.eq(ResourceEntity::getBookTypeId, type.getId());
            Wrapper.orderBy(true, true, ResourceEntity::getPageView);
            Wrapper.last("LIMIT 6");
            List<ResourceEntity> list1 = resourceService.list(Wrapper);
            map.put("resource", list1);
            list.add(map);
        }
        return R.ok(list);
    }

    @Override
    public R getResources(Long id, Page page) {
        page.setSize(9);
        LambdaQueryWrapper<ResourceEntity> Wrapper = Wrappers.lambdaQuery();
        Wrapper.eq(ResourceEntity::getBookTypeId, id);
        //Wrapper.orderBy(true, true, ResourceEntity::getPageView);
        return R.ok(resourceService.page(page, Wrapper));
    }

    @Override
    public ResponseEntity<String> downloadAndParseEpub(String epubUrl) {
       //String s = "http://10.100.24.103:9000/lengleng/" + epubUrl;
        epubUrl = "http://10.100.24.103:9000"+epubUrl.replace("https://zhongtai.zhongjiaoyuntu.com:9002","");
        try {
            URL url = new URL(epubUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            InputStream inputStream;

            if (connection.getResponseCode() >= 400) {
                inputStream = connection.getErrorStream();
            } else {
                inputStream = connection.getInputStream();
            }

            try (BufferedInputStream in = new BufferedInputStream(inputStream)) {
                // 解析EPUB文件
                Book book = (new EpubReader()).readEpub(in);

                // 获取HTML内容
                StringBuilder htmlContent = new StringBuilder();
                int i = 1;
                for (nl.siegmann.epublib.domain.Resource resource : book.getContents()) {
                    String content = new String(resource.getData());
                    content = saveImages(content, i);
                    htmlContent.append(content);
                    i++;
                }

                return ResponseEntity.ok()
                        .contentType(MediaType.TEXT_HTML)
                        .body(htmlContent.toString());
            }
        } catch (IOException e) {
            log.info("epub异常:{}",e);
            e.printStackTrace();
            return ResponseEntity.badRequest().body("处理EPUB文件时发生错误。");
        }
    }

    private String saveImages(String content, int chapterNumber) {
        int i = 0;
        while (content.contains("data:image/png;base64,")) {
            int startIndex = content.indexOf("data:image/png;base64,");
            int endIndex = content.indexOf("\"", startIndex);
            String base64Data = content.substring(startIndex + 22, endIndex);

            // Save image to file
            String fileName = "chapter_" + chapterNumber + "_image_" + i + ".png";
            saveImageToFile(base64Data, fileName);

            // Replace Base64 data with file path
            content = content.replace("data:image/png;base64," + base64Data, fileName);
            i++;
        }

        return content;
    }

    private void saveImageToFile(String base64Data, String fileName) {
        try {
            byte[] imageBytes = Base64.getDecoder().decode(base64Data);
            try (FileOutputStream imageOutputStream = new FileOutputStream(fileName)) {
                imageOutputStream.write(imageBytes);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private String unicode(String url) {
        try {
            String s = "http://61.163.243.7:9999/digitallibrary/bookExposure/lengleng/Book/";
            String[] segments = url.split("/");
            int length = segments.length;
            if (length >= 2) {
                String segment = segments[length - 2];
                String segment1 = segments[length - 1];
                System.out.println(segments[length - 2] + "/" + segments[length - 1]);
                String encodedStr = URLEncoder.encode(segment, StandardCharsets.UTF_8.toString());
                String encodedStr1 = URLEncoder.encode(segment1, StandardCharsets.UTF_8.toString());
                s = s + encodedStr + "/" + encodedStr1;
            }

            return s;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
